<template>
    <div class="monitor-tab">
        <!-- 全局加载遮罩 -->
        <a-spin :spinning="initialLoading" size="large" tip="正在加载数据...">
            <!-- 外层tabs - 端口管理 -->
            <div class="outer-tabs">
                <div class="tabs-header">
                    <div class="tabs-container">
                        <div 
                            v-for="port in ports" 
                            :key="port.id"
                            class="tab-item"
                            :class="{ active: activePortId === port.id }"
                            @click="switchPort(port.id)"
                        >
                            <a-icon type="api" class="tab-icon" />
                            <span class="tab-title">{{ port.name }}</span>
                            <a-icon 
                                type="close" 
                                class="tab-close"
                                @click.stop="closePort(port.id)"
                            />
                        </div>
                    </div>
                    <div class="tabs-actions">
                        <a-button type="primary" size="small" icon="plus" @click="addPort">添加端口</a-button>
                        <a-button 
                            v-if="ports.length > 0 && activePortId" 
                            size="small" 
                            icon="setting" 
                            @click="showPortManageModal"
                        >
                            {{ getCurrentPortName() }}属性
                        </a-button>
                    </div>
                </div>
                
                <!-- 主要内容区域 -->
                <div v-if="activePortId" class="main-content">
                    <!-- 左侧设备列表 -->
                    <div class="device-list-panel">
                        <div class="panel-header">
                            <h3>设备列表</h3>
                            <div class="panel-actions">
                                <a-button type="primary" size="small" icon="plus" @click="addDevice">添加设备</a-button>
                                <a-button size="small" icon="setting" @click="showDeviceManageModal">管理</a-button>
                            </div>
                        </div>
                        <div class="device-list">
                            <div 
                                v-for="device in devices" 
                                :key="device.id"
                                class="device-item"
                                :class="{ active: activeDeviceId === device.id }"
                                draggable="true"
                                @click="switchDevice(device.id)"
                                @dragstart="onDragStart($event, device)"
                                @dragover="onDragOver($event)"
                                @drop="onDrop($event)"
                            >
                                <span v-if="activeDeviceId === device.id" class="selected-triangle" />
                                <div class="device-info">
                                    <div class="device-name">
                                        <a-icon type="cluster" class="device-icon" />
                                        {{ device.name }}
                                    </div>
                                </div>
                                <div v-if="activeDeviceId === device.id" class="device-actions">
                                    <a-icon 
                                        type="edit" 
                                        class="device-edit"
                                        @click.stop="editDevice(device.id)"
                                    />                                    
                                    <a-icon 
                                        type="delete" 
                                        class="device-close"
                                        @click.stop="closeDevice(device.id)"
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 右侧设备监控表格 -->
                    <div v-if="activeDeviceId" class="monitor-panel">
                        <variable-list-panel
                            :active-device-id="activeDeviceId"
                            :device-name="getCurrentDeviceName()"
                            :devices="devices"
                            :port-proto-type="getCurrentPortProtoType()"
                            :port-name="getCurrentPortName()"
                            @data-updated="handleVariableDataUpdated"
                        />
                    </div>
                    
                    <!-- 空状态 -->
                    <div v-else class="empty-state">
                        <a-empty description="请选择一个设备查看监控数据" />
                    </div>
                </div>
                
                <!-- 无数据时的空状态 -->
                <div v-else-if="!initialLoading" class="empty-state">
                    <a-empty description="暂无端口数据，请先添加端口" />
                </div>
            </div>
        </a-spin>

        <!-- 端口设置弹窗 -->
        <port-settings-modal 
            :visible="portModalVisible"
            :port-data="editingPortData"
            @ok="handlePortModalOk"
            @cancel="handlePortModalCancel"
        />

        <!-- 设备管理弹框 -->
        <a-modal
            title="设备管理"
            :visible="deviceManageVisible"
            :footer="null"
            width="800px"
            :body-style="{ maxHeight: '70vh', padding: '16px' }"
            @cancel="handleDeviceManageCancel"
        >
            <div class="manage-content">
                <div class="manage-actions">
                    <a-button type="primary" icon="plus" @click="showAddDeviceForm">添加设备</a-button>
                    <a-button icon="reload" @click="refreshDevices">刷新</a-button>
                </div>
                <a-table
                    :columns="deviceManageColumns"
                    :data-source="paginatedDevicesForTable"
                    row-key="id"
                    size="small"
                    :pagination="false"
                    :loading="deviceTableLoading"
                >
                    <template slot="status" slot-scope="text, record">
                        <span class="status-indicator" :class="record.status">
                            {{ getStatusText(record.status) }}
                        </span>
                    </template>
                    <template slot="action" slot-scope="text, record">
                        <a-button type="link" icon="edit" @click="editDeviceInModal(record.id)" />
                        <a-button type="link" icon="delete" @click="deleteDeviceInModal(record.id)" />
                    </template>
                </a-table>
                <div class="table-footer">
                    <a-pagination
                        v-model="deviceManageCurrentPage"
                        :total="devicesForTable.length"
                        :page-size="deviceManagePageSize"
                        :show-size-changer="true"
                        :show-quick-jumper="true"
                        :show-total="total => `共 ${total} 条`"
                        :page-size-options="['10', '20', '50', '100']"
                        @change="handleDeviceManagePageChange"
                        @showSizeChange="handleDeviceManageSizeChange"
                    />
                </div>
            </div>
        </a-modal>
        
        <!-- 新的设备属性弹窗 -->
        <device-properties-modal
            :visible="devicePropertiesModalVisible"
            :device-data="editingDeviceData"
            :port-proto-type="getCurrentPortProtoType()"
            @ok="handleDevicePropertiesOk"
            @cancel="handleDevicePropertiesCancel"
        />
    </div>
</template>

<script>
import PortSettingsModal from '@/components/MonitorTab/PortSettingsModal.vue'
import DevicePropertiesModal from '@/components/MonitorTab/DevicePropertiesModal.vue'
import tabManager from '@/api/tab-manager'
import { mapGetters } from 'vuex'
import VariableListPanel from '@/components/MonitorTab/VariableListPanel.vue'
import { cloneDeep } from 'lodash'
import { getGatewayConfig } from '@/config/gateway-config'

export default {
    name: 'MonitorTab',
    components: {
        PortSettingsModal,
        DevicePropertiesModal,
        VariableListPanel
    },
    props: {
        selectedKey: { type: String, required: true }
    },
    data() {
        return {
            // 外层tabs数据
            ports: [],
            activePortId: null,
            
            // 内层tabs数据
            devices: [],
            activeDeviceId: null,
            
            // 加载状态
            initialLoading: false,
            deviceTableLoading: false,
            
            // 设备管理弹窗分页配置
            deviceManageCurrentPage: 1,
            deviceManagePageSize: 10,
            
            // 弹框控制
            portModalVisible: false,
            editingPortData: null,
            deviceManageVisible: false,
            devicePropertiesModalVisible: false,
            
            // 表单数据
            editingDeviceData: null,
            
            // 设备管理表格列配置
            deviceManageColumns: [
                { title: '设备名称', dataIndex: 'name', width: 120 },
                { title: '地址', dataIndex: 'address', width: 120 },
                { title: '状态', dataIndex: 'status', width: 80, scopedSlots: { customRender: 'status' } },
                { title: '描述', dataIndex: 'description', width: 150 },
                { title: '操作', dataIndex: 'action', width: 100, scopedSlots: { customRender: 'action' } }
            ]
        }
    },
    computed: {
        ...mapGetters('groupTree', ['selectedDeviceId', 'selectedGroupId', 'selectedDeviceInfo', 'selectedGroupInfo']),
        
        devicesForTable() {
            return Array.isArray(this.devices)
                ? this.devices.map(this.mapDeviceToTableRow)
                : []
        },
        
        // 分页后的设备表格数据
        paginatedDevicesForTable() {
            const startIndex = (this.deviceManageCurrentPage - 1) * this.deviceManagePageSize
            const endIndex = startIndex + this.deviceManagePageSize
            return this.devicesForTable.slice(startIndex, endIndex)
        }
    },
    
    watch: {
        // 监听选中设备ID的变化
        selectedDeviceId: {
            handler(newDeviceId, oldDeviceId) {
                console.log('🔄 [MonitorTab] 选中设备ID变化:', { 
                    old: oldDeviceId, 
                    new: newDeviceId 
                })
                
                // 设置全局的分组设备ID，供CefSharp接口使用
                if (newDeviceId !== oldDeviceId) {
                    console.log('🔄 [MonitorTab] 设置全局分组设备ID:', newDeviceId)
                    this.$store.dispatch('global/setCurrentGroupDeviceId', newDeviceId)
                }
                
                // 当选中设备发生变化时，重新加载所有数据
                if (newDeviceId !== oldDeviceId) {
                    if (newDeviceId) {
                        // 有新的设备ID，进行完整初始化
                        console.log('🚀 [MonitorTab] 检测到新的分组设备，开始重新初始化...')
                        
                        // 只有在真正的分组设备切换时才强制重置（从一个有效ID切换到另一个有效ID）
                        const isGroupDeviceSwitch = oldDeviceId && newDeviceId && oldDeviceId !== newDeviceId
                        if (isGroupDeviceSwitch) {
                            // 强制重置activePortId和activeDeviceId，确保即使ID相同也会触发更新
                            console.log('🔄 [MonitorTab] 检测到分组设备切换，强制重置活动状态，防止ID相同导致的不更新问题')
                            const oldActivePortId = this.activePortId
                            const oldActiveDeviceId = this.activeDeviceId
                            
                            // 先设置为null，强制触发watch
                            this.activePortId = null
                            this.activeDeviceId = null
                            
                            console.log('🔄 [MonitorTab] 已重置活动状态:', {
                                reason: '分组设备切换',
                                oldActivePortId,
                                oldActiveDeviceId,
                                newActivePortId: this.activePortId,
                                newActiveDeviceId: this.activeDeviceId
                            })
                        } else {
                            console.log('🔄 [MonitorTab] 非分组设备切换，使用正常初始化流程')
                        }
                        
                        // 移除额外的then回调，让loadInitialData自己处理完整的初始化流程
                        // switchPort方法中已经会正确设置activeDeviceId
                        this.loadInitialData()
                    } else {
                        // 设备ID被清空，清理数据
                        console.log('🧹 [MonitorTab] 分组设备被清空，清理数据')
                        this.ports = []
                        this.devices = []
                        this.activePortId = null
                        this.activeDeviceId = null
                    }
                }
                
            },
            immediate: false // 不立即执行，因为 mounted 中已经会调用 loadInitialData
        },
        
        // 监听当前活动端口ID的变化
        activePortId: {
            handler(newPortId, oldPortId) {
                console.log('🔄 [MonitorTab] 活动端口ID变化:', { 
                    old: oldPortId, 
                    new: newPortId,
                    isForceRefresh: oldPortId === null && newPortId !== null,
                    timestamp: new Date().toISOString()
                })
                
                // 活动端口变化时的处理逻辑已移至switchPort方法中，避免重复调用loadDevices
                // 这里的watch主要用于监控和调试
            },
            immediate: false
        },
        
        // 监听当前活动设备ID的变化
        activeDeviceId: {
            handler(newDeviceId, oldDeviceId) {
                console.log('🔄 [MonitorTab] 活动设备ID变化:', { 
                    old: oldDeviceId, 
                    new: newDeviceId,
                    isForceRefresh: oldDeviceId === null && newDeviceId !== null,
                    isReset: newDeviceId === null && oldDeviceId !== null,
                    timestamp: new Date().toISOString()
                })
                
                // 这里可以添加其他需要在设备切换时执行的逻辑
                if (newDeviceId !== oldDeviceId) {
                    if (newDeviceId === null) {
                        console.log('🔄 [MonitorTab] 设备ID被重置为null（强制刷新中）')
                    } else if (oldDeviceId === null) {
                        console.log('✅ [MonitorTab] 设备切换完成（从null恢复），通知子组件')
                    } else {
                        console.log('✅ [MonitorTab] 设备切换完成（正常切换），通知子组件')
                    }
                }
            },
            immediate: false
        }
    },
    
    async mounted() {
        console.log('🚀 [MonitorTab] 组件 mounted，检查 Vuex 状态')
        console.log('📋 [MonitorTab] 当前选中设备ID:', this.selectedDeviceId)
        console.log('📋 [MonitorTab] 当前选中设备信息:', this.selectedDeviceInfo)
        console.log('📋 [MonitorTab] 当前选中分组ID:', this.selectedGroupId)
        console.log('📋 [MonitorTab] 当前选中分组信息:', this.selectedGroupInfo)
        console.log('📋 [MonitorTab] Vuex store 状态:', this.$store.state.groupTree)
        
        // 设置初始的全局分组设备ID
        if (this.selectedDeviceId) {
            console.log('🔄 [MonitorTab] 设置初始的全局分组设备ID:', this.selectedDeviceId)
            this.$store.dispatch('global/setCurrentGroupDeviceId', this.selectedDeviceId)
        }
        
        await this.loadInitialData()
    },
    
    beforeDestroy() {
        // 组件销毁前清除全局分组设备ID
        console.log('🧹 [MonitorTab] 组件销毁，清除全局分组设备ID')
        this.$store.dispatch('global/clearCurrentGroupDeviceId')
    },
    
    methods: {
        // 初始化数据加载
        async loadInitialData() {
            console.log('🚀 [MonitorTab] 开始初始化数据加载')
            
            // 检查是否有选中的分组设备，如果没有则等待
            if (!this.selectedDeviceId) {
                console.log('⚠️ [MonitorTab] 暂无选中分组设备，等待用户选择...', {
                    selectedDeviceId: this.selectedDeviceId,
                    vuexState: this.$store.state.groupTree
                })
                return
            }
            
            // 开始加载
            this.initialLoading = true
            
            try {
                // 先加载端口数据
                await this.loadPorts()
                
                // 检查端口是否加载成功，只有在有端口数据时才进行切换
                if (this.ports && this.ports.length > 0) {
                    console.log('🔄 [MonitorTab] 端口加载成功，开始切换到第一个端口', { 
                        portsCount: this.ports.length, 
                        firstPortId: this.ports[0].id 
                    })
                    await this.switchPort(this.ports[0].id)
                } else {
                    console.log('⚠️ [MonitorTab] 没有端口数据，清除设备列表和活动状态', { 
                        selectedDeviceId: this.selectedDeviceId,
                        portsCount: this.ports ? this.ports.length : 'null'
                    })
                    // 清除设备列表和活动状态
                    this.devices = []
                    this.activePortId = null
                    this.activeDeviceId = null
                }
                
                console.log('✅ [MonitorTab] 初始化数据加载完成', { 
                    ports: this.ports.length, 
                    devices: this.devices.length,
                    activePortId: this.activePortId,
                    activeDeviceId: this.activeDeviceId,
                    timestamp: new Date().toISOString()
                })
            } catch (error) {
                console.error('❌ [MonitorTab] 初始化数据失败:', error)
                this.$message.error('数据加载失败')
            } finally {
                // 结束加载
                this.initialLoading = false
            }
        },
        
        // 加载端口数据
        async loadPorts() {
            console.log('🔍 [MonitorTab] 加载端口数据')
            try {
                // 获取选中的分组设备ID
                const selectedDeviceId = this.selectedDeviceId
                console.log('📋 [MonitorTab] 使用分组设备ID加载端口:', selectedDeviceId)
                
                // 如果没有选中设备，跳过端口加载或使用默认值
                if (!selectedDeviceId) {
                    console.log('⚠️ [MonitorTab] 没有选中分组设备，跳过端口加载')
                    this.ports = []
                    return
                }
                
                const response = await tabManager.monitor.getPortList(selectedDeviceId)
                
                // 检查响应状态
                if (response.code === 0) {
                    this.ports = JSON.parse(response.data)
                    console.log('✅ [MonitorTab] 端口数据加载成功', { 
                        count: this.ports.length, 
                        groupDeviceId: selectedDeviceId,
                        portsData: this.ports
                    })
                } else {
                    console.warn('⚠️ [MonitorTab] 端口数据加载异常:', response.msg)
                    this.$message.warning(response.msg || '获取端口数据异常')
                    this.ports = []
                }
            } catch (error) {
                console.error('❌ [MonitorTab] 加载端口失败:', error)
                this.$message.error('端口数据加载失败')
                this.ports = []
            }
        },
        
        // 加载设备数据
        async loadDevices() {
            console.log('🔍 [MonitorTab] 加载设备数据', { activePortId: this.activePortId })
            try {
                // 如果没有选中端口，跳过设备加载
                if (!this.activePortId) {
                    console.log('⚠️ [MonitorTab] 没有选中端口，跳过设备加载')
                    this.devices = []
                    return
                }
                
                const response = await tabManager.monitor.getDeviceList(this.activePortId)
                console.log('📋 [MonitorTab] 设备数据响应:', response)
                
                // 检查响应状态
                if (response.code === 0) {
                    console.log('📋 [MonitorTab] response.data 类型:', typeof response.data)
                    console.log('📋 [MonitorTab] response.data 内容:', response.data)
                    
                    // 处理 JSON 解析
                    try {
                        if (typeof response.data === 'string') {
                            this.devices = JSON.parse(response.data)
                        } else {
                            // 如果已经是对象或数组，直接使用
                            this.devices = response.data || []
                        }
                        
                        console.log('📋 [MonitorTab] 解析后的设备数据:', this.devices)
                        console.log('✅ [MonitorTab] 设备数据加载成功', { 
                            count: this.devices.length, 
                            portId: this.activePortId 
                        })
                    } catch (parseError) {
                        console.error('❌ [MonitorTab] JSON解析失败:', parseError)
                        console.log('📋 [MonitorTab] 原始数据:', response.data)
                        this.devices = []
                    }
                } else {
                    console.warn('⚠️ [MonitorTab] 设备数据加载异常:', response.message)
                    this.$message.warning(response.message || '获取设备数据异常')
                    this.devices = []
                }
            } catch (error) {
                console.error('❌ [MonitorTab] 加载设备失败:', error)
                this.$message.error('设备数据加载失败')
                this.devices = []
            }
        },
        
        // 端口相关方法
        async switchPort(portId) {
            console.log('🔄 [MonitorTab] 切换端口开始', { 
                portId, 
                currentActivePortId: this.activePortId,
                currentActiveDeviceId: this.activeDeviceId,
                isForceRefresh: this.activePortId !== portId || this.activePortId === null
            })
            
            // 先设置端口ID
            this.activePortId = portId
            
            // 重新加载当前端口的设备列表
            console.log('📋 [MonitorTab] 开始加载端口设备数据...')
            await this.loadDevices()
            
            console.log('📋 [MonitorTab] 设备数据加载完成', {
                devicesCount: this.devices.length,
                devices: this.devices.map(d => ({ id: d.id, name: d.name }))
            })
            
            // 强制重置activeDeviceId，确保即使设备ID相同也会触发更新
            const oldActiveDeviceId = this.activeDeviceId
            
            // 确保设备数据加载完成后再设置activeDeviceId
            if (this.devices && this.devices.length > 0) {
                const newActiveDeviceId = this.devices[0].id
                console.log('🔄 [MonitorTab] 准备设置新的活动设备ID', {
                    oldDeviceId: oldActiveDeviceId,
                    newDeviceId: newActiveDeviceId,
                    isSameId: oldActiveDeviceId === newActiveDeviceId,
                    willForceUpdate: true
                })
                
                // 如果ID相同，先设置为null再设置为目标值，强制触发watch
                if (oldActiveDeviceId === newActiveDeviceId) {
                    console.log('⚠️ [MonitorTab] 设备ID相同，强制触发更新')
                    this.activeDeviceId = null
                    // 使用nextTick确保null值的设置已经生效
                    await this.$nextTick()
                }
                
                this.activeDeviceId = newActiveDeviceId
                
                console.log('✅ [MonitorTab] 端口切换成功', { 
                    portId, 
                    deviceId: this.activeDeviceId, 
                    deviceCount: this.devices.length 
                })
            } else {
                console.log('⚠️ [MonitorTab] 没有设备数据，清空活动设备ID', {
                    oldDeviceId: this.activeDeviceId
                })
                this.activeDeviceId = null
                console.log('✅ [MonitorTab] 端口切换成功，但无设备', { portId })
            }
        },
        
        async closePort(portId) {
            console.log('🗑️ [MonitorTab] 删除端口', { portId })
            try {
                await this.$confirm({
                    title: '确认删除',
                    content: '确定要删除这个端口吗？删除后相关设备将一并移除。',
                    onOk: async() => {
                        await tabManager.monitor.deletePort(portId)
                        this.$message.success('端口删除成功')
                        // 只移除被删除的端口，不整体刷新
                        this.ports = this.ports.filter(p => p.id !== portId)
                        // 如果关闭的是当前激活的端口，切换到其他端口
                        if (this.activePortId === portId) {
                            if (this.ports.length > 0) {
                                this.switchPort(this.ports[0].id)
                            } else {
                                this.activePortId = null
                                this.activeDeviceId = null
                            }
                        }
                        console.log('✅ [MonitorTab] 端口删除操作完成', { portId })
                    }
                })
            } catch (error) {
                console.error('❌ [MonitorTab] 删除端口失败:', error)
                this.$message.error('删除端口失败')
            }
        },
        
        addPort() {
            // 需要根据GATEWAY_CONFIGS中的硬件信息(serialPortCount)，来限制添加端口的数量
            // 根据设备类型获取updateMode
            const deviceType = this.selectedDeviceInfo.gatewayType || this.selectedDeviceInfo.deviceType
            const gatewayConfig = getGatewayConfig(deviceType)
            const serialPortCount = gatewayConfig.hardwareInfo.serialPortCount
            if (this.ports.length >= serialPortCount) {
                this.$message.error('端口数量已达到最大限制' + serialPortCount)
                return
            }
            console.log('➕ [MonitorTab] 打开添加端口弹窗')
            this.editingPortData = null
            this.portModalVisible = true
        },
        
        async showPortManageModal() {
            console.log('🔍 [MonitorTab] 打开端口管理弹窗，先刷新端口数据')
            
            // 先刷新端口数据以确保获取最新数据
            await this.loadPorts()
            
            // 然后获取当前端口的最新数据
            const port = this.ports.find(p => p.id === this.activePortId) || null
            console.log('🔍 [MonitorTab] 获取到最新端口数据', port?.extra)
            
            if (port) {
                // 先清空 editingPortData 确保 Vue 能检测到变化
                this.editingPortData = null
                
                // 使用 $nextTick 确保响应式更新
                await this.$nextTick()
                
                // 然后设置新的数据
                if (typeof port.extra === 'string') {
                    this.editingPortData = JSON.parse(port.extra)
                } else {
                    this.editingPortData = cloneDeep(port)
                }
                
                console.log('🔍 [MonitorTab] 设置编辑数据:', this.editingPortData)
                
                // 确保数据设置完成后再显示弹窗
                await this.$nextTick()
                this.portModalVisible = true
            } else {
                console.error('❌ [MonitorTab] 未找到当前端口数据')
                this.$message.error('未找到端口数据，请重新选择端口')
            }
        },
        
        // 设备相关方法
        switchDevice(deviceId) {
            console.log('🔄 [MonitorTab] 手动切换设备', { 
                oldDeviceId: this.activeDeviceId,
                newDeviceId: deviceId,
                willTriggerWatch: this.activeDeviceId !== deviceId
            })
            
            this.activeDeviceId = deviceId
            
            console.log('✅ [MonitorTab] 设备切换成功', { 
                deviceId,
                timestamp: new Date().toISOString()
            })
        },
        
        editDevice(deviceId) {
            console.log('✏️ [MonitorTab] 编辑设备', { deviceId })
            // 根据设备ID找到对应的设备
            const device = this.devices.find(d => d.id === deviceId)
            if (device) {
                console.log('📋 [MonitorTab] 找到设备:', device)
                if (typeof device.extra === 'string') {
                    this.editingDeviceData = JSON.parse(device.extra)
                } else {
                    this.editingDeviceData = cloneDeep(device)
                }
                this.devicePropertiesModalVisible = true
            } else {
                console.error('❌ [MonitorTab] 未找到设备:', deviceId)
                this.$message.error('未找到指定设备')
            }
        },
        
        async closeDevice(deviceId) {
            console.log('🗑️ [MonitorTab] 删除设备', { deviceId })
            try {
                await this.$confirm({
                    title: '确认删除',
                    content: '确定要删除这个设备吗？',
                    onOk: async() => {
                        await tabManager.monitor.deleteDevice(deviceId)
                        this.$message.success('设备删除成功')
                        
                        // 直接从设备列表中移除删除的设备，而不是重新请求所有数据
                        const deviceIndex = this.devices.findIndex(d => d.id === deviceId)
                        if (deviceIndex !== -1) {
                            this.devices.splice(deviceIndex, 1)
                            console.log('✅ [MonitorTab] 设备已从列表中移除', { deviceId })
                        }
                        
                        // 如果删除的是当前激活的设备，切换到其他设备
                        if (this.activeDeviceId === deviceId) {
                            if (this.devices.length > 0) {
                                this.activeDeviceId = this.devices[0].id
                            } else {
                                this.activeDeviceId = null
                            }
                        }
                        console.log('✅ [MonitorTab] 设备删除操作完成', { deviceId })
                    }
                })
            } catch (error) {
                console.error('❌ [MonitorTab] 删除设备失败:', error)
                this.$message.error('删除设备失败')
            }
        },
        
        async addDevice() {
            try {
                // 需要根据GATEWAY_CONFIGS中的硬件信息(deviceCount)，来限制添加设备的数量
                // 根据设备类型获取updateMode
                const deviceType = this.selectedDeviceInfo.gatewayType || this.selectedDeviceInfo.deviceType
                const gatewayConfig = getGatewayConfig(deviceType)
                const deviceCount = gatewayConfig.hardwareInfo.deviceCount
                // 获取硬件数量
                const res = await tabManager.monitor.getHardwareCount(this.selectedDeviceId)
                if (res.code === 0) {
                    console.log('🔍 [MonitorTab] 获取硬件数量成功 deviceCount', deviceCount)
                    const data = JSON.parse(res.data)
                    if (data.device >= deviceCount) {
                        this.$message.error('设备数量已达到最大限制' + deviceCount)
                        return
                    }                    
                }

                console.log('➕ [MonitorTab] 打开添加设备弹窗')
                this.editingDeviceData = null
                this.devicePropertiesModalVisible = true                
            } catch (error) {
                console.error('❌ [MonitorTab] 添加设备失败:', error)
                this.$message.error('添加设备失败')
            }
        },
        
        showDeviceManageModal() {
            console.log('⚙️ [MonitorTab] 打开设备管理弹窗')
            this.deviceManageVisible = true
        },
        
        async refreshDevices() {
            console.log('🔄 [MonitorTab] 刷新设备数据', { activePortId: this.activePortId })
            this.deviceTableLoading = true
            try {
                await this.loadDevices()
                this.$message.success('设备数据已刷新')
                console.log('✅ [MonitorTab] 设备数据刷新成功')
            } catch (error) {
                console.error('❌ [MonitorTab] 刷新设备数据失败:', error)
                this.$message.error('刷新失败')
            } finally {
                this.deviceTableLoading = false
            }
        },
        
        // 工具方法
        mapDeviceToTableRow(raw) {
            // 要判断设备管理对话框是否显示，如果不显示，不执行
            if (!this.deviceManageVisible) {
                return {}
            }
            console.log('🔍 [MonitorTab] mapDeviceToTableRow:', raw)
            let extra = {}
            if (raw.extra && typeof raw.extra === 'string') {
                extra = JSON.parse(raw.extra) 
            }
            const data = extra
            return {
                id: raw.id,
                name: raw.name,
                address: data.extra.address,
                // 如果status为空，则默认为离线
                status: data.extra.status || 'offline',
                description: data.description
            }
        },
        getStatusText(status) {
            const statusMap = {
                'online': '在线',
                'offline': '离线',
                'error': '异常',
                'normal': '正常'
            }
            return statusMap[status] || status
        },
        
        // 弹框处理方法
        handleDeviceManageCancel() {
            this.deviceManageVisible = false
        },
        
        // 设备表单处理
        showAddDeviceForm() {
            console.log('➕ [MonitorTab] 打开添加设备表单')
            this.editingDeviceData = null
            this.devicePropertiesModalVisible = true
        },
        
        editDeviceInModal(deviceId) {
            // console.log('✏️ [MonitorTab] 编辑设备', { deviceId })
            // // record 是设备ID，需要从 devices 中获取完整的设备数据
            // const device = this.devices.find(d => d.id === deviceId)
            // if (device) {
            //     console.log('📋 [MonitorTab] 找到设备:', device)
            //     this.editingDeviceData = cloneDeep(device)
            //     this.devicePropertiesModalVisible = true
            // } else {
            //     console.error('❌ [MonitorTab] 未找到设备:', deviceId)
            //     this.$message.error('未找到指定设备')
            // }
            this.editDevice(deviceId)
        },
        
        async deleteDeviceInModal(deviceId) {
            console.log('🗑️ [MonitorTab] 在弹窗中删除设备', { deviceId })
            await this.closeDevice(deviceId)
        },
        
        async handleDevicePropertiesOk(formData) {
            console.log('💾 [MonitorTab] 保存设备属性', { formData, editingDevice: this.editingDeviceData })
            try {
                if (this.editingDeviceData && this.editingDeviceData.id) {
                    // Edit
                    console.log('✏️ [MonitorTab] 更新设备', { deviceId: this.editingDeviceData.id })
                    formData.monitor_port_id = this.activePortId
                    const res = await tabManager.monitor.updateDevice(this.editingDeviceData.id, JSON.stringify(formData))
                    if (res.code === 0 && res.data) {
                        this.$message.success('设备更新成功')
                        console.log('✅ [MonitorTab] 设备更新成功', res.data)
                        // 直接更新设备列表中的对应项目，而不是重新请求
                        const data = JSON.parse(res.data)
                        const deviceIndex = this.devices.findIndex(d => d.id === this.editingDeviceData.id)
                        if (deviceIndex !== -1) {
                            // 更新现有设备的属性
                            const updateDevice = {
                                id: data.id,
                                name: formData.name || data.name,
                                description: formData.description || data.description || '',
                                monitor_port_id: this.activePortId,
                                ...data // 包含后端返回的其他属性
                            }
                            this.devices[deviceIndex] = updateDevice
                            this.refreshDevices()
                            console.log('✅ [MonitorTab] 设备列表已更新:', deviceIndex)
                            console.log('✅ [MonitorTab] 设备列表已更新:', this.devices[deviceIndex])
                        }                        
                    } else {
                        this.$message.error(res.msg || '设备更新失败')
                        return
                    }
                } else {
                    // Add
                    formData.monitor_port_id = this.activePortId
                    console.log('➕ [MonitorTab] 创建新设备', { portId: formData.monitor_port_id })
                    const res = await tabManager.monitor.createDevice(JSON.stringify(formData))
                    
                    // 检查返回状态
                    if (res.code === 0 && res.data) {
                        this.$message.success('设备创建成功')
                        console.log('✅ [MonitorTab] 设备创建成功')
                        
                        const data = JSON.parse(res.data)
                        // 直接添加新设备到列表中，而不是重新请求
                        const newDevice = {
                            id: data.id,
                            name: formData.name || data.name,
                            description: formData.description || data.description || '',
                            monitor_port_id: this.activePortId,
                            ...data // 包含后端返回的其他属性
                        }
                        
                        // 添加到设备列表
                        this.devices.push(newDevice)
                        
                        // 自动切换到新设备
                        this.activeDeviceId = newDevice.id
                        console.log('✅ [MonitorTab] 新设备已添加到列表:', newDevice)
                    } else {
                        this.$message.error(res.msg || '设备创建失败')
                        return
                    }
                    
                    this.devicePropertiesModalVisible = false
                    return
                }
                this.devicePropertiesModalVisible = false
            } catch (error) {
                console.error('❌ [MonitorTab] 设备操作失败:', error)
                this.$message.error('操作失败')
            }
        },

        handleDevicePropertiesCancel() {
            console.log('❌ [MonitorTab] 取消设备属性编辑')
            this.devicePropertiesModalVisible = false
        },
        
        // 拖拽相关方法
        onDragStart(event, device) {
            event.dataTransfer.setData('text', JSON.stringify(device))
        },
        
        onDragOver(event) {
            event.preventDefault()
        },
        
        onDrop(event) {
            event.preventDefault()
            const data = JSON.parse(event.dataTransfer.getData('text'))
            this.switchDevice(data.id)
        },
        
        getCurrentDeviceName() {
            const device = this.devices.find(d => d.id === this.activeDeviceId)
            return device ? device.name : '未命名设备'
        },

        getCurrentPortName() {
            const port = this.ports.find(p => p.id === this.activePortId)
            return port ? port.name : '端口'
        },

        getCurrentPortProtoType() {
            const port = this.ports.find(p => p.id === this.activePortId)

            console.log('🔍 [MonitorTab] getCurrentPortProtoType:', {
                activePortId: this.activePortId,
                ports: this.ports,
                foundPort: port,
                portKeys: port ? Object.keys(port) : [],
                protoType: port ? port.proto_type : null
            })

            if (!port) {
                console.log('⚠️ [MonitorTab] 未找到当前端口')
                return ''
            }

            // 首先检查端口本身的 proto_type
            if (port.proto_type) {
                console.log('✅ [MonitorTab] 从端口本身获取 proto_type:', port.proto_type)
                return port.proto_type
            }

            // 然后检查 extra 中的 proto_type
            if (port.extra) {
                try {
                    let extra
                    // 需要判断是否是json字符串
                    if (typeof port.extra === 'string') {
                        extra = JSON.parse(port.extra)
                    } else {
                        extra = port.extra
                    }
                    
                    if (extra.proto_type) {
                        console.log('✅ [MonitorTab] 从端口扩展数据获取 proto_type:', extra.proto_type)
                        return extra.proto_type
                    }
                } catch (error) {
                    console.error('❌ [MonitorTab] 解析端口扩展数据失败:', error)
                }
            }

            console.log('⚠️ [MonitorTab] 未找到 proto_type，返回空字符串')
            return ''
        },

        async handlePortModalOk(formData) {
            console.log('💾 [MonitorTab] 保存端口设置', { formData, editingPort: this.editingPortData })
            try {
                if (this.editingPortData && this.editingPortData.id) {
                    // Edit
                    formData.group_device_id = this.selectedDeviceId
                    const res = await tabManager.monitor.updatePort(this.editingPortData.id, JSON.stringify(formData))
                    if (res.code === 0 && res.data) {
                        let port = JSON.parse(res.data)
                        this.$message.success('端口更新成功')
                        
                        // 使用接口返回的数据更新端口列表
                        const portIndex = this.ports.findIndex(p => p.id === this.editingPortData.id)
                        if (portIndex !== -1) {
                            port.extra = JSON.stringify(formData)
                            this.ports[portIndex] = port
                        }
                    } else {
                        this.$message.error(res.msg || '端口更新失败')
                        return
                    }
                } else {
                    // Add - 添加选中的分组设备 ID
                    console.log('➕ [MonitorTab] 创建新端口')
                    
                    // 获取选中的分组设备 ID
                    const selectedDeviceId = this.selectedDeviceId
                    if (selectedDeviceId) {
                        formData.group_device_id = selectedDeviceId
                        console.log('📋 [MonitorTab] 设置分组设备 ID:', selectedDeviceId)
                    } else {
                        console.log('⚠️ [MonitorTab] 未选中分组设备，使用默认值')
                    }
                    
                    const res = await tabManager.monitor.createPort(JSON.stringify(formData))
                    if (res.code === 0 && res.data) {
                        const port = JSON.parse(res.data)
                        this.ports.push(port)
                        this.$message.success('端口创建成功')
                        // 切换到新创建的端口
                        this.switchPort(port.id)
                        console.log('✅ [MonitorTab] 端口创建成功', port)
                    } else {
                        this.$message.error(res.msg || '端口创建失败')
                        return
                    }
                }

                this.portModalVisible = false
                this.editingPortData = null // 清除编辑状态
            } catch (error) {
                console.error('❌ [MonitorTab] 端口操作失败:', error)
                this.$message.error('操作失败')
            }
        },

        handlePortModalCancel() {
            console.log('❌ [MonitorTab] 取消端口设置编辑')
            this.portModalVisible = false
            this.editingPortData = null // 清除编辑状态
        },

        handleVariableDataUpdated() {
            console.log('🔄 [MonitorTab] 变量数据已更新')
            // 由于变量管理已经移到VariableListPanel组件，此方法暂时不需要执行特定操作
        },
        
        // 设备管理弹窗分页方法
        handleDeviceManagePageChange(page, pageSize) {
            console.log('🔄 [MonitorTab] 设备管理页码变化:', { page, pageSize })
            this.deviceManageCurrentPage = page
        },
        
        handleDeviceManageSizeChange(current, size) {
            console.log('🔄 [MonitorTab] 设备管理每页数量变化:', { current, size })
            this.deviceManageCurrentPage = 1 // 重置到第一页
            this.deviceManagePageSize = size
        }
    }
}
</script>

<style scoped>
.monitor-tab {
    height: 100%;
    display: flex;
    flex-direction: column;
}

/* 加载状态样式 */
.monitor-tab >>> .ant-spin-container {
    height: 100%;
}
.monitor-tab >>> .ant-spin-blur {
    opacity: 0.3;
}
.monitor-tab >>> .ant-spin-blur .outer-tabs {
    pointer-events: none;
}
.outer-tabs {
    flex: 1;
    display: flex;
    flex-direction: column;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
}
.main-content {
    flex: 1;
    display: flex;
    overflow: hidden;
}
.device-list-panel {
    width: 280px;
    border-right: 1px solid #d9d9d9;
    display: flex;
    flex-direction: column;
    background: #fafafa;
}
.monitor-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #fff;
}
.panel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    border-bottom: 1px solid #d9d9d9;
    background: #fff;
}
.panel-header h3 {
    margin: 0;
    font-size: 14px;
    font-weight: 500;
    color: #333;
}
.panel-actions {
    display: flex;
    gap: 8px;
}
.device-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
}
.device-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
    margin-bottom: 8px;
    background: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
    user-select: none;
}
.device-item:hover {
    border-color: #1890ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}
.device-item.active {
    background: #e6f7ff;
    border-color: #1890ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
    position: relative;
}
.device-item.dragging {
    opacity: 0.5;
}
.selected-triangle {
    position: absolute;
    left: 0;
    top: 0;
    width: 0;
    height: 0;
    border-top: 20px solid #1890ff;
    border-right: 20px solid transparent;
    z-index: 2;
    display: block;
}
.device-info {
    flex: 1;
    min-width: 0;
}
.device-name {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: flex;
    align-items: center;
}
.device-icon {
    margin-right: 6px;
    font-size: 14px;
}
.device-address {
    font-size: 12px;
    color: #666;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.device-actions {
    display: flex;
    align-items: center;
}
.device-close {
    font-size: 16px;
    color: #999;
    opacity: 0.7;
    transition: opacity 0.3s;
    margin-left: 8px;
}
.device-close:hover {
    opacity: 1;
    color: #ff4d4f;
}
.device-edit {
    font-size: 16px;
    color: #999;
    opacity: 0.7;
    transition: opacity 0.3s;
}
.device-edit:hover {
    opacity: 1;
    color: #1890ff;
}
.empty-state {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fafafa;
}
.tabs-header {
    display: flex;
    align-items: center;
    background: #fafafa;
    border-bottom: 1px solid #d9d9d9;
    padding: 8px 12px;
}
.tabs-container {
    flex: 1;
    display: flex;
    gap: 4px;
    overflow-x: auto;
}
.tab-item {
    display: flex;
    align-items: center;
    padding: 6px 12px;
    background: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    white-space: nowrap;
    transition: all 0.3s;
}
.tab-item:hover {
    border-color: #1890ff;
}
.tab-item.active {
    background: #1890ff;
    border-color: #1890ff;
    color: #fff;
}
.tab-icon {
    margin-right: 6px;
    font-size: 14px;
}
.tab-title {
    margin-right: 8px;
}
.tab-close {
    font-size: 12px;
    opacity: 0.7;
    transition: opacity 0.3s;
}
.tab-close:hover {
    opacity: 1;
}
.tabs-actions {
    display: flex;
    gap: 8px;
    margin-left: 12px;
}
.manage-content {
    display: flex;
    flex-direction: column;
    max-height: calc(70vh - 120px);
}
.manage-actions {
    margin-bottom: 16px;
    flex-shrink: 0;
    display: flex;
    gap: 12px;
}
.manage-content >>> .ant-table-wrapper {
    flex: 1;
    overflow: auto;
}
.table-footer {
    margin-top: 16px;
    display: flex;
    justify-content: center;
    flex-shrink: 0;
}

/* 滚动条样式 */
.tabs-container::-webkit-scrollbar,
.device-list::-webkit-scrollbar {
    width: 4px;
    height: 4px;
}
.tabs-container::-webkit-scrollbar-track,
.device-list::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 2px;
}
.tabs-container::-webkit-scrollbar-thumb,
.device-list::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 2px;
}
.tabs-container::-webkit-scrollbar-thumb:hover,
.device-list::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 拖拽样式 */
.device-item[draggable="true"] {
    cursor: grab;
}
.device-item[draggable="true"]:active {
    cursor: grabbing;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .main-content {
        flex-direction: column;
    }
    .device-list-panel {
        width: 100%;
        height: 200px;
        border-right: none;
        border-bottom: 1px solid #d9d9d9;
    }
}
.device-status {
    display: flex;
    align-items: center;
    font-size: 12px;
    margin-top: 4px;
}
.device-status.online {
    color: #52c41a;
}
.device-status.offline {
    color: #d9d9d9;
}
.device-status.error {
    color: #ff4d4f;
}
.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 4px;
    background-color: currentColor;
}
</style> 